package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"net"
	"time"
)

const (
	SERVER_NETWORK = "tcp"
	SERVER_ADDRESS = "127.0.0.1:8085"
	DELIMITER      = '\t'
)

func printLog(format string, args ...interface{}) {
	fmt.Printf("%s", fmt.Sprintf(format, args...))
}

func main() {
	var listener net.Listener
	listener, err := net.Listen(SERVER_NETWORK, SERVER_ADDRESS)
	if err != nil {
		printLog("Listen Error :%s\n", err)
		return
	}
	defer listener.Close()
	printLog("Got listener for the server.(local address :%s)\n", listener.Addr())

	for {
		conn, err := listener.Accept()
		if err != nil {
			printLog("Accpet Error :%s\n", err)
			return
		}
		printLog("Established a connection with a client application.(remote address :%s)\n", conn.RemoteAddr())
		go handleConn(conn)
	}
}

func handleConn(conn net.Conn) {
	defer conn.Close()
	reader := bufio.NewReader(conn)
	for {
		conn.SetReadDeadline(time.Now().Add(10 * time.Second))
		readBytes, err := reader.ReadBytes(DELIMITER)
		if err != nil {
			if err != io.EOF {
				printLog(" read from Remote Client err :%s\n", err)
			}
			return
		}
		respMsg := fmt.Sprintf("The message from server :%s", string(readBytes[:len(readBytes)-1]))

		var buffer bytes.Buffer
		buffer.WriteString(respMsg)
		buffer.WriteByte(DELIMITER)
		n, err := conn.Write(buffer.Bytes())
		if err != nil {
			printLog(" Write Error :%s(Server)\n", err)
			return
		}
		printLog("Send reponse(Written %d bytes):%s (Server)\n", n, respMsg)
	}
}
